import { RequestMethod } from "../lib/defines";
import { MemberBase, RoomBase } from "../utils/types";
import { ChatModeEnums } from "../utils/enums";

export type CreateQuery = {
  type: ChatModeEnums;
  /**
   * 所属用户
   */
  member: MemberBase;

  /**
   * 所属房间
   */
  room: RoomBase;
}

export default function invite (app) {
  const { socket, rooms } = app.locals;
  const { userId } = socket.handshake.query;
  /**
   * 创建一个房间
   *
   * @param data
   * @param cb
   */
  socket.on(RequestMethod.invite, function inviteMember (data: CreateQuery, cb) {
    const { room, member } = data;
    const { rooms, intercom } = app.locals;
    const __room = rooms[room.classId]
    const __socket = intercom[member.userId]

    if (!__room) {
      return cb && cb({status: 'error', message: 'room not find!'})
    }

    if (!__socket) {
      return cb && cb({status: 'error', message: 'member not online!'})
    }

    const mediaOptions= __room.getMediaOption();
    const options = { room: __room.json(),  mediaOptions };

    socket.setInviteUser(member)

    try {
      /**
       * 3分钟的等待接听时间
       */
      socket.to(__socket.id).timeout(1000 * 60 * 3).emit('invite', options, (error, [data]) => {
        if (error) {
          // 超时未接听
          if (cb) {
            cb({ status: 'error', resolve: 'created' })
          }
          return;
        }

        /**
         * 对方同意加入
         *
         * 1. 通知邀请者本人
         * 2. 通知房间中的其他人
         */
        socket.emit('invited', { data: member, status: data?.status });
        socket.broadcast.in(room.classId).emit('invited', { data: member, status: data?.status });

        // 回调
        if (cb) {
          cb({ status: 'ok', resolve: 'created' })
        }
      });

    } catch (e) {
      console.error(e)
    }
  });


  /**
   * 拒绝加入
   */
  socket.on(RequestMethod.rejectInvite, function dissolve ({ room, member }: CreateQuery, cb) {
    const __room = rooms[room.classId]

    room = Object.assign(room, __room.json())

    /**
     * 2秒 等待接听时间
     */
    socket
      .timeout(1000 * 2)
      .to(room.classId)
      .emit('rejectInvite', { room, member }, () => {
        __room.getMembers().forEach(member => {
          member.stop(userId)
        })

        // 回调
        if (cb) {
          cb({ status: 'ok', resolve: 'rejectInvite' })
        }
      });
  });
}
